<template>
  <div class="layout-container">
    <split-pane split="vertical" :min-percent="17" :default-percent="19" :max-percent="50">
      <template slot="paneL">
        <div class="left-container">
          <el-input
            v-model="filterText"
            placeholder="输入部门名称进行过滤"
          />
          <el-tree
            ref="tree"
            style="margin-top: 20px"
            class="filter-tree"
            :data="orgIdTreeOptions"
            :props="defaultProps"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <!--可以根据情况，以数据类型来显示不同的图标或图片-->
              <i v-if="(data.children && data.children.length) || data.parentId === '0'" :class="node.expanded ?'co-icon-zg-folder-opened-fill' : 'co-icon-folder_opened'" />
              <i v-else class="el-icon-document" />
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </template>
      <template slot="paneR">
        <div class="right-container">
          <basic-page-vxe
            ref="basePage"
            list-api="querySysUser"
            del-api="deleteSysUser"
            export-api="exportSysUser"
            :export-name="$route.meta.title"
            :search-form="basicData.searchForm"
            :search-handle="basicData.searchHandle"
            :search-other-data="basicData.searchData"
            :columns="basicData.columns"
          />
        </div>
      </template>
    </split-pane>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px" style="width: 100%">
        <el-form-item label="员工编号" prop="username">
          <el-input v-model="temp.username" placeholder="请输入" :disabled="dialogStatus==='update'" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="temp.nickname" placeholder="请输入" minlength="2" maxlength="64" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" label="密码" prop="password">
          <el-input v-model="temp.password" placeholder="请输入" show-password minlength="6" maxlength="31" clearable autocomplete="new-password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="请输入" maxlength="100" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" placeholder="请输入" class="input-with-select" maxlength="20" clearable>
            <el-select slot="prepend" v-model="temp.prefix" placeholder="请选择" style="width: 90px">
              <el-option label="+86" value="86" />
              <el-option label="+87" value="87" />
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="temp.roleId" placeholder="请选择" clearable class="filter-item" style="width: 100%">
            <el-option v-for="item in roleIdOptions" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构" prop="orgId">
          <el-cascader
            v-model="temp.orgId"
            style="width: 360px"
            filterable
            :options="orgIdOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'title',emitPath: false }"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSysUser, updateSysUser, queryRoleName, querySysOrgTree } from '@/api/admin'
import splitPane from 'vue-splitpane'
export default {
  name: '',
  components: {
    splitPane
  },
  directives: {},
  filters: {},
  data() {
    return {
      basicData: {
        columns: [
          { config: { title: '员工编号', field: 'username' }, type: 'copy' },
          { config: { title: '姓名', field: 'nickname' }},
          { config: { title: '手机号', field: 'mobile' }},
          { config: { title: '角色', field: 'roleIdCn' }},
          { config: { title: '所属机构', field: 'orgIdCn' }},
          { config: { title: '状态', field: 'status', width: 70 }, type: 'render',
            render: (h, scope) => {
              if (scope.row.status === 1) {
                return (
                  <el-tag effect='plain' type='success'>正常</el-tag>
                )
              } else {
                return (
                  <el-tag effect='plain' type='danger'>禁用</el-tag>
                )
              }
            } },
          { config: { title: '创建日期', width: '160', field: 'createTime' }, type: 'time' },
          {
            config: {
              title: '操作',
              width: '180'
            }, type: 'render',
            render: (h, scope) => {
              return (
                <div>
                  <el-button plain size='mini' type='primary' v-permission="'update'" onClick={() => this.handleUpdate(scope.row)}><i class='el-icon-edit'></i> 编辑</el-button>
                  <el-button plain size='mini' type='danger' v-permission="'delete'" onClick={() => this.$refs.basePage.handleDelete(scope.row)}><i class='el-icon-delete'></i> 删除</el-button>
                </div>
              )
            }
          }
        ],
        searchData: {
          orgId: ''
        },
        searchForm: [
          { type: 'Input', label: '员工编号', prop: 'username', width: '180px' },
          { type: 'Select', label: '状态', prop: 'status', options: [{ name: '正常', value: '1' }, { name: '禁用', value: '0' }], width: '180px' }
        ],
        searchHandle: [
          { label: '新增', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleCreate() } }
        ]
      },
      typ: [],
      detail: {},
      roleIdOptions: [],
      orgIdOptions: [],
      orgIdTreeOptions: [],
      orgName: '',
      temp: {
        id: undefined,
        status: 1,
        prefix: '86'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        username: [{ required: true, validator: this.checkUsername, trigger: ['blur', 'change'] }],
        password: [{ required: true, validator: this.checkPassword, trigger: ['blur', 'change'] }],
        email: [{ required: true, message: '请输入邮箱地址！', trigger: 'blur' }, { type: 'email', message: '请输入正确的邮箱地址！', trigger: ['blur', 'change'] }],
        mobile: [{ required: true, validator: this.checkMobile, trigger: ['blur', 'change'] }],
        roleId: [{ required: true, message: '请选择角色！', trigger: 'change' }],
        orgId: [{ required: true, message: '请选择所属机构！', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态！', trigger: 'change' }]
      },
      downloadLoading: false,
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getType()
  },
  mounted() {
  },
  methods: {
    handleNodeClick(val) {
      this.basicData.searchData.orgId = val.id
      this.$refs.basePage.getList()
    },
    filterNode(value, data) {
      if (!value) return true
      console.log(data)
      return data.title.indexOf(value) !== -1
    },
    // 业务逻辑
    getType() {
      queryRoleName().then(response => {
        this.roleIdOptions = response.data
      })
      querySysOrgTree().then(response => {
        this.orgIdOptions = response.data.list
        this.orgIdTreeOptions = response.data.list
        this.orgIdTreeOptions.unshift({ title: '全部', id: '', value: '', key: '', parentId: '0' })
        this.basicData.searchForm[2].options = response.data.list
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 1,
        prefix: '86',
        orgId: this.basicData.searchData.orgId
      }
    },
    handleCreate() {
      this.resetTemp()
      this.orgName = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addSysUser(this.temp).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          const tempData = {}
          tempData.id = this.temp.id
          tempData.username = this.temp.username
          tempData.nickname = this.temp.nickname
          tempData.email = this.temp.email
          tempData.mobile = this.temp.mobile
          tempData.prefix = this.temp.prefix
          tempData.roleId = this.temp.roleId
          tempData.orgId = this.temp.orgId
          tempData.status = this.temp.status
          updateSysUser(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleReset() {
      this.getType()
      this.$refs.basePage.getList()
    },
    checkUsername(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入用户名！'))
      } else {
        if (value.length > 2 && value.length < 65) {
          callback()
        } else {
          return callback(new Error('用户名长度最小为3最大为64！'))
        }
      }
    },
    checkPassword(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入密码！'))
      } else {
        if (value.length > 5 && value.length < 32) {
          callback()
        } else {
          return callback(new Error('密码长度最小为6最大为31！'))
        }
      }
    },
    checkMobile(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入手机号！'))
      } else {
        const reg = /^1\d{10}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号！'))
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .custom-tree-node{
    .co-icon-zg-folder-opened-fill, .co-icon-folder_opened{
      color: #f5d672;
      margin-right: 10px;
      font-size: 16px;
    }
  }
</style>
